package rs.daolao.syc.admin.account.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import rs.dalao.syc.common.ex.ServiceException;
import rs.dalao.syc.common.pojo.authentication.CurrentPrincipal;
import rs.dalao.syc.common.pojo.vo.PageData;
import rs.dalao.syc.common.response.ServiceCode;
import rs.daolao.syc.admin.account.dao.cache.IUserCacheRepository;
import rs.daolao.syc.admin.account.dao.persist.repository.IUserRepository;
import rs.daolao.syc.admin.account.dao.search.IUserSearchRepository;
import rs.daolao.syc.admin.account.pojo.entity.Doctor;
import rs.daolao.syc.admin.account.pojo.entity.User;
import rs.daolao.syc.admin.account.pojo.vo.*;
import rs.daolao.syc.admin.account.service.IUserService;

import java.util.List;

/**
 * 处理用户数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 2.0
 */
@Slf4j
@Service
public class UserServiceAdminImpl implements IUserService {

    @Value("10")
    private Integer defaultQueryPageSize;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IUserCacheRepository userCacheRepository;
    @Autowired
    private IUserSearchRepository iUserSearchRepository;

    public UserServiceAdminImpl() {
        log.debug("创建业务类对象：UserServiceImpl");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除用户】的业务，参数：{}", id);
        if (id == 1) {
            String message = "删除用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        Object queryResult = userRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "删除用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        log.debug("即将执行删除数据，参数：{}", id);
        int rows = userRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除用户失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        log.debug("即将执行删除关联数据，参数：{}", id);

        if (rows < 1) {
            String message = "删除用户失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        log.debug("即将删除缓存中的账号状态数据，无参数");
        userCacheRepository.deleteUserState(id);
    }


    @Override
    public void setEnable(Long userId) {
        log.debug("开始处理【启用用户】的业务，参数：{}", userId);
        updateEnableById(userId, ENABLE_STATE_ON);
    }

    @Override
    public void setDisable(Long userId) {
        log.debug("开始处理【禁用用户】的业务，参数：{}", userId);
        updateEnableById(userId, ENABLE_STATE_OFF);
    }

    @Override
    public void setDocDisable(Long docId) {
        updateDocEnableById(docId,ENABLE_STATE_ON);
    }

    @Override
    public void setDocEnable(Long docId) {
        updateDocEnableById(docId,ENABLE_STATE_OFF);
    }
    @Override
    public UserStandardVO getStandardById(Long userId) {
        log.debug("开始处理【根据ID查询用户】业务，参数：{}", userId);
        UserStandardVO currentUser = userRepository.getStandardById(userId);
        if (currentUser == null) {
            String message = "获取用户详情失败，尝试访问的用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return currentUser;
    }

    @Override
    public PageData<UserListItemVO> userList(Integer pageNum) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}", pageNum);
        return userRepository.UserList(pageNum, defaultQueryPageSize);
    }
    @Override
    public PageData<DoctorListVO> doctorList(Integer pageNum) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}", pageNum);
        return userRepository.doctorList(pageNum, defaultQueryPageSize);
    }
    @Override
    public PageData<UserListItemVO> userList(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        return userRepository.UserList(pageNum, pageSize);
    }

    @Override
    public PageData<DoctorListVO> DoctorList(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        return userRepository.doctorList(pageNum, pageSize);
    }

    @Override
    public void rebuildSearch() {
        log.debug("开始处理从ES中【查询用户】的业务");
        iUserSearchRepository.deleteAll();
        Integer pageNum = 1;
        Integer pageSize = 2;
        Integer maxPage;
        PageData<UsersSearchVO> userListItemVOPageData;
        do {
            userListItemVOPageData = userRepository.userSearch(pageNum, pageSize);
            maxPage = userListItemVOPageData.getMaxPage();
            List<UsersSearchVO> list = userListItemVOPageData.getList();
            iUserSearchRepository.saveAll(list);
            pageNum++;
        } while (pageNum <=maxPage);

    }

    @Override
    public List<UsersSearchVO> customQueryUser(String title) {
        return iUserSearchRepository.customQuery(title);
    }


    private void updateEnableById(Long id, Integer enable) {
        log.debug("开始处理【{}用户】的业务，ID：{}，目标状态：{}", ENABLE_STATE_TEXT[enable], id, enable);
        if (id == 0) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        UserStandardVO queryResult = userRepository.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，当前用户已经处于"
                    + ENABLE_STATE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        User user = new User();
        user.setId(id);
        user.setEnable(enable);
        log.debug("即将修改数据，参数：{}", user);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        if (enable == 1) {
            userCacheRepository.setUserDisabled(id);
        }
    }
    private void updateDocEnableById(Long id, Integer enable) {
        log.debug("开始处理【{}用户】的业务，ID：{}，目标状态：{}", ENABLE_STATE_TEXT[enable], id, enable);
        if (id == 0) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        DoctorStandardVO queryResult = userRepository.getSearchByDoctorId(id);
        if (queryResult == null) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，当前用户已经处于"
                    + ENABLE_STATE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        Doctor doctor = new Doctor();
        doctor.setId(id);
        doctor.setEnable(enable);
        log.debug("即将修改数据，参数：{}", doctor);
        int rows = userRepository.updateByDoctorId(doctor);
        if (rows != 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        if (enable == 1) {
            userCacheRepository.setUserDisabled(id);
        }
    }
    @Override
    public void logout(CurrentPrincipal currentPrincipal) {
        Long userId = currentPrincipal.getId();
        boolean deleteResult = userCacheRepository.deleteUserState(userId);//清除缓存
        if (!deleteResult) {
            String message = "操作失败，用户数据错误！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
    }




}
